import sceneManager from './sceneManager';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import * as T from 'three';

class ModelEventManager{
    highlightNode :T.Object3D[]= [];
    initEvent () {

        window.addEventListener('resize', () => {
            const sceneBox = document.querySelector('#scene') as HTMLElement;
            const { width, height } = sceneBox!.getBoundingClientRect();
        sceneManager.renderer!.setSize(width, height);
        sceneManager.camera!.aspect = width / height;
        sceneManager.camera!.updateProjectionMatrix();
        });

        const controls = new OrbitControls(sceneManager.camera!, sceneManager.renderer!.domElement);
        controls.addEventListener('change', () => {
        sceneManager.renderer!.render(sceneManager.scene!, sceneManager.camera!);
        });
        sceneManager.renderer?.domElement.addEventListener('mousedown', this.modelClickHandler.bind(this, this.registerPointer));
    }
    modelClickHandler(callback:any, e:MouseEvent ){
        const raycaster = new T.Raycaster();
        const x = (e.clientX / window.innerWidth) * 2 - 1;
        const y = -(e.clientY / window.innerHeight) * 2 + 1;
        const vec = new T.Vector2(x, y);
        raycaster.setFromCamera(vec, sceneManager.camera!);
        const intersects:T.Intersection<T.Mesh>[] = raycaster.intersectObjects(sceneManager.scene!.children);
        // if (intersects.length > 0) {
        //     // 高亮显示相交的模型
        //     intersects[0].object.material.color.set(0xff0000);
        // }
        callback({ button: e.button, tempPath: intersects, position:{ x, y, left:e.offsetX, bottom:e.offsetY } });
    }
    registerPointer(props:any){
        if(props.button === 0){
            this.registerLeftPoint(props);
        }else if (props.button === 2){
            this.registerRightPoint(props);
        }
    }
    registerLeftPoint(props:any){
        this.highLightModel(props.tempPath);
    }
    highLightModel(nodes:any){
        nodes[0].object.material.color.set(0xff0000);
        this.highlightNode.push(nodes[0]);
    }
    registerRightPoint(props:any){

    }
    addAnimate(mesh: any) {
        mesh.rotateX(0.01);
        // mesh.scale(2, 1, 2,);
        sceneManager.renderer!.render(sceneManager.scene!, sceneManager.camera!);
        requestAnimationFrame(this.addAnimate.bind(this, mesh));
    }
}

export default new ModelEventManager();
